package leetcode.BinaryTree;

import java.util.*;
import java.util.concurrent.PriorityBlockingQueue;

public class LevelOrder {

    /**
     * 二叉树层序遍历
     *
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int count = queue.size();
            List<Integer> temp = new ArrayList();
            while (count-- > 0) {
                TreeNode tempNode = queue.poll();
                temp.add(tempNode.val);

                if (tempNode.left != null) {
                    queue.add(tempNode.left);
                }
                if (tempNode.right != null) {
                    queue.add(tempNode.right);
                }
            }
            result.add(temp);

        }
        return result;

    }

    public List<List<Integer>> levelOrderRecursion(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null) return result;
        executor(root,result,0);
        return result;
    }

    public void executor(TreeNode node,List<List<Integer>> result,int high){
        if(node == null) return;
        if(result.size() < high+1) result.add(new ArrayList<>());
        result.get(high).add(node.val);
        high++;
        executor(node.left,result,high);
        executor(node.right,result,high);
    }


    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(9);
        TreeNode node3 = new TreeNode(20);
        TreeNode node4 = new TreeNode(15);
        TreeNode node5 = new TreeNode(7);


        node1.right = node3;
        node1.left = node2;
        node3.right = node5;
        node3.left = node4;

        System.out.println(Arrays.asList(levelOrder(node1)));

    }
}
